<template>
  <view>
    <van-notice-bar left-icon="volume-o" text="订单里面的所有商品以及对下一节点的进行。" />
    <van-notify id="van-notify" />
    <!-- 列表部分 -->
    <scroll-view 
      class="list-container" 
      scroll-y="true" 
      lower-threshold="100" 
      :style="{ height: '100vh' }"
    >
      <view class="list-item-title">订单编号：{{ orderNo }}</view>
      
      <!-- 循环渲染每个商品 -->
      <view 
        class="list-item" 
        v-for="(item, index) in list" 
        :key="index"
      >
        <view class="list-item-title">物品编号：{{ item.goodsCode }}</view>
        <view class="list-item-description">物品名称：{{ item.goodsName }}</view>
        <view class="list-item-description">所在仓库：{{ item.warehouseName }}</view>
        <view class="list-item-description">物品数量：{{ item.goodsNum }}</view>
        <view class="list-item-description">物品单位：{{ item.unitName }}</view>
        
        <!-- 生产时间选择器 -->
        <view class="list-item-description">
          生产时间：{{ item.productionDate ? item.productionDate : '未选择' }}
        </view>
        <picker mode="date" @change="onProductionDateChange(index, $event)" :value="item.productionDate" v-if="orderStatus == 2">
          <view class="picker">
            {{ item.productionDate ? item.productionDate : '选择生产时间' }}
          </view>
        </picker>

        <!-- 过期时间选择器 -->
        <view class="list-item-description">
          过期时间：{{ item.expiryDate ? item.expiryDate : '未选择' }}
        </view>
        <picker mode="date" @change="onExpirationDateChange(index, $event)" :value="item.expiryDate" v-if="orderStatus == 2">
          <view class="picker">
            {{ item.expiryDate ? item.expiryDate : '选择过期时间' }}
          </view>
        </picker>

        <!-- 拍照按钮 -->
        <button @click="takePhoto(index)" v-if="orderStatus == 2" class="procurement-add">拍照并上传</button>
        
        <!-- 展示已选择的图片 -->
        <view v-if="item.fileList.length > 0">
          <view v-for="(file, idx) in item.fileList" :key="idx" style="margin-top: 10px;">
            <image :src="file.img" mode="widthFix" style="width: 100%;" />
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="loading" class="loading-text">加载中...</view>

      <!-- 请求失败提示 -->
      <view v-if="requestFailed" class="loading-text">请求失败，请稍后再试</view>
      
      <view class="button-container">
        <van-button round type="warning" v-if="orderStatus == 1" @click="cancelOrder(orderNo)" class="procurement-add">取消订单</van-button>
        <van-button round type="info" v-if="orderStatus == 1" @click="notarizeOrder(orderNo)" class="procurement-add">确认订单</van-button>
        <van-button round type="info" v-if="orderStatus == 2" @click="goNotarizeGoods()" class="procurement-add">订单收货</van-button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderNo: '',            // 订单编号
      orderStatus: '',        // 订单状态
      list: [],               // 存储订单商品列表
      loading: false,         // 加载状态
      requestFailed: false,   // 请求失败标志
    };
  },
  onLoad(query) {
    // 获取页面传递的参数并初始化数据
    this.orderNo = query.orderNo;
    this.orderStatus = query.orderStatus;
    this.fetchData(); // 请求数据
  },
  methods: {
    notarizeOrder(id) {
      const url = this.$C.api_url + `api/order/orderNotarize/${id}`;
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'PUT',
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            uni.showToast({
              title: '确认成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/procurement/procurement',
              });
            }, 1000);
          } else {
            uni.showToast({
              title: '确认订单失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '取消失败，请稍后再试',
            icon: 'none'
          });
        },
      });
    },
    cancelOrder(id) {
      const url = this.$C.api_url + `api/order/orderCancel/${id}`;
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'PUT',
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            uni.showToast({
              title: '取消成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/procurement/procurement',
              });
            }, 1000);
          } else {
            uni.showToast({
              title: '取消订单失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '取消失败，请稍后再试',
            icon: 'none'
          });
        },
      });
    },
    goNotarizeGoods() {
      const goodsConstruction = {
        orderNo: this.orderNo,
        goodsInventoryDTOList: this.list.map(item => ({
          inventoryId: item.inventoryId,
		  warehuseId: item.warehuseId,
          productionDate: item.productionDate,
          expiryDate: item.expiryDate,
          goodsImg: item.fileList.length > 0 ? item.fileList.map(file => file.img) : [],
        })),
      };
      const url = this.$C.api_url + 'api/order/orderSignFor';
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'POST',
        data: goodsConstruction,
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            uni.showToast({
              title: '收货成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/procurement/procurement',
              });
            }, 1000);
          } else {
            uni.showToast({
              title: '收货失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '请求失败，请稍后再试',
            icon: 'none'
          });
        },
      });
    },
    onProductionDateChange(index, event) {
      const date = event.detail.value;
      this.$set(this.list[index], 'productionDate', date);
    },
    onExpirationDateChange(index, event) {
      const date = event.detail.value;
      this.$set(this.list[index], 'expiryDate', date);
    },

    // 拍照并上传
    takePhoto(index) {
      // 如果已经拍摄5张图片，限制继续拍照
      if (this.list[index].fileList.length >= 5) {
        uni.showToast({
          title: '最多只能拍摄五张图片',
          icon: 'none'
        });
        return;
      }

      // 请求相机权限
      this.requestCameraPermission().then(() => {
        // 使用uni.chooseImage拍照
        uni.chooseImage({
          count: 1, // 选择一张图片
          sourceType: ['camera'], // 只选择摄像头拍摄
          success: (res) => {
            const filePath = res.tempFilePaths[0];

            // 将拍照图片添加到对应商品的fileList中
            this.$set(this.list[index], 'fileList', [...this.list[index].fileList, { img: filePath }]);

            // 上传图片
            this.uploadImage(filePath, index);
          },
          fail: (err) => {
            uni.showToast({
              title: '拍照失败，请重试',
              icon: 'none'
            });
          }
        });
      }).catch(() => {
        uni.showToast({
          title: '相机权限被拒绝，请开启相机权限',
          icon: 'none'
        });
      });
    },

    // 上传图片到服务器
    uploadImage(filePath, index) {
		let token = uni.getStorageSync('token');
      uni.uploadFile({
        url: this.$C.api_url + 'api/file/upload', // 替换为你的文件上传接口
        filePath: filePath,
        name: 'file',
		header:{
			'satoken':token
		},
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.code === 200) {

            const imgUrl = data.data; // 获取图片URL
            this.$set(this.list[index], 'fileList', this.list[index].fileList.map((file, idx) => {
              if (file.img === filePath) {
                file.img = imgUrl; // 更新为上传后的图片URL
              }
              return file;
            }));
          } else {
            uni.showToast({
              title: '上传失败，请稍后重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '上传失败，请稍后重试',
            icon: 'none'
          });
        },
      });
    },

    // 请求相机权限
    requestCameraPermission() {
      return new Promise((resolve, reject) => {
        uni.authorize({
          scope: 'scope.camera',
          success: resolve,
          fail: reject
        });
      });
    },

    // 获取订单商品数据
    fetchData() {
      this.loading = true;
      this.requestFailed = false;

      const url = this.$C.api_url + 'api/order/getOrderGoods';
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'GET',
        data: { orderNo: this.orderNo },
		header:{
			'satoken':token
		},
        success: (res) => {
          this.loading = false;
          const { goodsVos } = res.data.data || [];
          if (Array.isArray(goodsVos)) {
            this.list = goodsVos.map(item => ({
              ...item,
              fileList: [],
              productionDate: item.productionDate || null,
              expiryDate: item.expiryDate || null,
            }));
          }
        },
        fail: (err) => {
          this.loading = false;
          this.requestFailed = true;
        },
      });
    }
  }
};
</script>

<style scoped>
.list-container {
  padding: 10px;
}

.list-item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-text {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.list-item-title {
  font-size: 15px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.list-item-description {
  font-size: 14px;
  color: #160e1f;
  line-height: 1.6;
}
.procurement-add {
	display: flex;
  justify-content: center; /* 水平居中 */
}
.picker {
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  margin-top: 5px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.button-container {
  display: flex; /* 使用flex布局 */
  justify-content: center; /* 水平居中 */
  margin-bottom: 20px; /* 添加底部间距 */
}
</style>
